package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.commom.BaseContext;
import com.itheima.reggie.commom.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/*
@date 2022年08月03日10:31  TODO 查询购物车列表,暂时空实现,后期补充实现;
*/
@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        log.info("接收到添加购物车的请求:shoppingCart={}",shoppingCart);
        //查询用户购物车数据,判断是否存在所添加的菜品和套餐
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw=new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,currentId);
        //判断是否菜品一致
        lqw.eq(shoppingCart.getDishId()!=null,ShoppingCart::getDishId,shoppingCart.getDishId());
        //判断是否套餐一致
        lqw.eq(shoppingCart.getSetmealId()!=null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        ShoppingCart s1 = shoppingCartService.getOne(lqw);
        //存在update+1
        if(s1!=null){
          shoppingCart.setNumber(s1.getNumber()+1);
          shoppingCartService.updateById(s1);
          return R.success(s1);
        }else {
            //不存在insert
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(currentId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            return  R.success(shoppingCart);
        }

    }



    /**
     * 查看购物车, TODO 查询购物车列表,暂时空实现,后期补充实现;
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        LambdaQueryWrapper<ShoppingCart> lqw=new LambdaQueryWrapper<>();
        //用户id是否和当前线程id一致
        lqw.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        //排序,创建时间
        lqw.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list();
        return R.success(list);
    }

    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public  R<String> clean(){
      //从当前线程获取用户id
        Long currentUserId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqw=new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,currentUserId);
        shoppingCartService.remove(lqw);
        return  R.success("删除成功!");
    }
}
